<template>
	<view class="" style="background-color: #fff;">
		<uni-table style="min-width: 0px;" ref="table" :loading="false" border stripe :type="selectType" 
		:isSingle="isSingle" emptyText="暂无更多数据"
			@selection-change="_selectionChange" :data="bodyData" :rowKey="rowKey">

			<view id="head" class="tableHead" style="background-color: #fff;">
				<uni-tr :disabled="isSingle||checkDisabled">
					<uni-th v-for="(item, index) in headData" :key="index" :field="item.field" align="center" style="font-size: 18px;" :width="customWidth(item.width)">
						<view :style="{'width':customWidth(item.width)+'px','color':'#000'}" class="name">{{item.name}}
						</view>
					</uni-th>
				</uni-tr>
			</view>
			<!-- :width="customWidth(item.width)?customWidth(item.width):50" -->
			<!-- <uni-tr>
					<uni-th width="50" align="center">id</uni-th>
					rowspan 该列占的行数；colspan该列占的列数
					<uni-th field="createtime" sortable="true" @sort-change="sortChange" filter-type="date"
						dateType="daterange" returnType="String" :setDateRange="setDateRange"
						@filter-change="filterChange" width="150" colspan=1 rowspan=1 align="center">日期</uni-th>
					<uni-th field="userName" filter-type="select" :filter-data="filterData"
						@filter-change="filterChange" width="150" align="center">姓名</uni-th>
					<uni-th width="204" field="address" align="center">上海市普陀区金沙江路 1517 弄</uni-th>
					<uni-th width="204" align="center">设置</uni-th>
				</uni-tr> -->

			<view :style="{'height':listSumHeight+'px'}"></view>
			<!-- <view :style="{height:(swiperHeight-listSumHeight)+'px','overflow':'scroll'}"> -->
			<scroll-view id="scr" :style="{'height':scrollViewHeight+'px','width':'100%'}" scroll-y="true"
				:scroll-top="scrollTop" @scroll="listScroll">
				<uni-tr v-for="(body, index) in bodyData" :key="index" :keyValue="body[rowKey]" :id="('row_'+index)">
					<uni-td v-for="(head, index) in headData" :key="index" align="center" style="font-size: 18px;" >
						<view :style="{'width':customWidth(head.width)+'px','word-break':'break-all'}" class="name">
							{{ body[head.field] }}
						</view>
					</uni-td>
				</uni-tr>
				<!-- :width="head.width" -->
				<!-- 	<uni-td width="150" align="center">{{ item.date }}</uni-td>
					<uni-td width="150">
						<view class="name">{{ item.name }}</view>
					</uni-td>
					<uni-td width="204" align="center">{{ item.address }}</uni-td> -->
				<!-- <uni-td width="204" align="center">
						<view class="uni-group" style="display: flex;justify-items: center;">
							<button class="uni-button" size="mini" type="primary">修改</button>
							<button class="uni-button" size="mini" type="warn">删除</button>
						</view>
					</uni-td> -->
			</scroll-view>
			<!-- </view> -->
		</uni-table>
	</view>
</template>

<script>
	import * as SystemJs from '@/common/system.js'
	/**
	 * headData this.headData= [{field: 'id',name: 'id',width: "50"}] 表头内容
	 * bodyData  表体内容
	 * swiperHeight  表格的高度
	 * @property {String}  rowKey 获取整行数据的关键key
	 * isSingle  是否单选，true 是 false 否
	 * checkDisabled  是否选取勾选表头的复选框
	 * selectType  是否开启选择框  selection 开启， '' 为关闭
	 */
	export default {
		emits: ['selection-change'],
		props: {
			headData: {
				type: Array,
				default: []
			},
			bodyData: {
				type: Array,
				default: []
			},
			swiperHeight: {
				type: [String, Number],
				default: 0
			},
			rowKey: {
				type: String,
				default: 'id'
			},
			isSingle: {
				type: [Boolean, String],
				default: false
			},
			checkDisabled: {
				type: Boolean,
				default: false
			},
			selectType: {
				type: String,
				default: 'selection'
			}
			
		},
		data() {
			return {
				//滑动区域的高度(单位px)
				// swiperHeight: 0,
				listSumHeight: 0,
				scrollTop: 0,
				scrollViewHeight: 0,
				emptyHeight: 51 //表格无数据时提示语固定高度
			}
		},
		onPageScroll(e) {
			console.log(e)
		},
		created() {
			this.scrollViewHeight = this.swiperHeight - this.emptyHeight
		},
		onShow() {

			//动态设置swiper的高度
			this.$nextTick(() => {
				// var height = 0;
				// height = this.getByIdHeight("head");
				// console.log('he', height)
				// this.listSumHeight = height;
				//获取列表中汇总信息的高度
			});
		},
		watch: {
			//监听数据的变化
			bodyData: {
				handler(newVal, oldVal) {
					if (newVal != undefined && newVal.length > 0) {
						//因为使用了scrollView固定了高度，在没有获取到数据时，会先显示提示语，显示时高度变大有可能被隐藏
						//默认设置高度里边没有包含提示语的高度，所以当有数据后要默认增加上提示语所占高度，提高体验感，视觉上在有数据和没有时不会发生变化
						this.scrollViewHeight = this.swiperHeight - this.listSumHeight;
					} else {
						// console.log("新b")
						this.scrollViewHeight = (this.swiperHeight - this.listSumHeight - this.emptyHeight);
					}
				},
				immediate: true
			},
			headData: {
				handler(newVal, oldVal) {
					if (newVal != undefined && newVal.length > 0) {
						var timeout = setTimeout(() => {
							SystemJs.systemJs.getByIdHeight('head', this, 'listSumHeight')
							clearTimeout(timeout)
							
						}, 800)
					}
				},
				immediate: true
			},
			listSumHeight: {
				handler(newVal) {
					if (newVal != undefined && Number(newVal) > 0) {
						this.scrollViewHeight = (this.swiperHeight - this.listSumHeight - this
							.emptyHeight);
					}
				},
				immediate: true
			}
			
		},
		mounted() {
			// var timeout = setTimeout(() => {
			// 	SystemJs.systemJs.getByIdHeight('head', this, 'listSumHeight')
			// 	this.scrollViewHeight = (this.swiperHeight - this.listSumHeight);
			// 	clearTimeout(timeout)
			// }, 800)

		},
		methods: {
			/**
			 * 自动定位数据
			 */
			async autoScrollRow(index) {
				if (this.bodyData != undefined && this.bodyData.length > 0) {
					if (index) {
						var first = await this.getDomInfo('row_0');
						var end = await this.getDomInfo('row_' + (this.bodyData.length - 1))
						if (end && first) {
							if ((end.top - first.top) <= (this.swiperHeight - this.listSumHeight)) {
								return;
							}
						}
						var obj = await this.getDomInfo('row_' + index);
						if (first && obj) {
							this.scrollTop = obj.top - first.top
						}
					}
				}
			},
			getDomInfo(id) {
				return new Promise((resolve) => {
					let element = '#' + id;
					const query = uni.createSelectorQuery().in(this);
					query.select(element).boundingClientRect();
					query.selectViewport().scrollOffset();
					query.exec((res) => {
						console.log(res)
						if (res && res[0]) {
							resolve(res[0]);
						} else {
							resolve("");
						}
					});
				})
			},

			// 根据props中的width属性 自动匹配当前th的宽度(px)
			customWidth(width) {
				if (typeof width === 'number') {
					return width
				} else if (typeof width === 'string') {
					let regexHaveUnitPx = new RegExp(/^[1-9][0-9]*px$/g)
					let regexHaveUnitRpx = new RegExp(/^[1-9][0-9]*rpx$/g)
					let regexHaveNotUnit = new RegExp(/^[1-9][0-9]*$/g)
					if (width.match(regexHaveUnitPx) !== null) { // 携带了 px
						return width.replace('px', '')
					} else if (width.match(regexHaveUnitRpx) !== null) { // 携带了 rpx
						let numberRpx = Number(width.replace('rpx', ''))
						let widthCoe = uni.getSystemInfoSync().screenWidth / 750
						return Math.round(numberRpx * widthCoe)
					} else if (width.match(regexHaveNotUnit) !== null) { // 未携带 rpx或px 的纯数字 String
						return width
					} else { // 不符合格式
						return ''
					}
				} else {
					return ''
				}
			},
			//列表滑动时的监听事件(改变顶部汇总信息栏的背景透明度)
			listScroll(e) {
				// console.log(e);
				var listTop = e.detail.scrollTop; //距离顶部的长度
				// console.log(listTop)
			},
			//根据id获取布局的高度
			getByIdHeight(id) {
				let element = '#' + id;
				var nHeight = 0;
				const query = uni.createSelectorQuery().in(this);
				query.select(element).boundingClientRect();
				query.selectViewport().scrollOffset();
				query.exec((res) => {
					if (res && res[0]) {
						nHeight = res[0].height;
					}
				});
				return nHeight;
			},
			getHeight() {
				this.$nextTick(() => {
					var height = 0;
					height = this.getByIdHeight("head");
					console.log('he', height)
					this.listSumHeight = height;
					//获取列表中汇总信息的高度

				});
				return this.listSumHeight;
			},
			_selectionChange(e) {
				this.$emit('selection-change', e)
			},
			toggleRowSelection(row, selected) {
				this.$refs.table.toggleRowSelection(row, selected);
			}
		}
	}
</script>

<style>
	.uni-container {
		width: 100%;
		height: 100%;
	}

	/* //表头固定样式 */
	.tableHead {
		font-weight: bold;
		color: #333333;
		background: #F4F6FF;
		z-index: 20;
		position: absolute;
		top: 0;
	}
</style>